﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using RanchBuddy.Core.Domain.Impl;
using StructureMap;

namespace RanchBuddy.Core.Services.Impl
{
    [Pluggable("Default")]
    public class WebCookie : IWebCookie
    {
        
        public string Username
        {
            set { SetCookie("Username", value, DateTime.Now, new TimeSpan(30, 0, 0, 0)); }
            get { return GetCookieValue("Username");  }
        }

        public string UsernameKey
        {
            set { SetCookie("UsernameKey", Cryptography.Encrypt(value, "tm-es@as"), DateTime.Now, new TimeSpan(30,0,0,0)); }
            get
            {
                string result = "";
                if(!String.IsNullOrEmpty(GetCookieValue("UsernameKey")))
                    result = Cryptography.Decrypt(GetCookieValue("UsernameKey"), "tm-es@as");
                return result;
            }
        }

        public void ClearCookies()
        {
            foreach (string key in HttpContext.Current.Request.Cookies.AllKeys)
            {
                HttpCookie cookie = GetCookie(key);
                if (cookie != null)
                {
                    cookie.Expires = DateTime.Now;
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }   
        }

        private HttpCookie GetCookie(string Name)
        {
            HttpCookie result = null;
            if (HttpContext.Current.Request.Cookies[Name] != null)
                result = HttpContext.Current.Request.Cookies[Name];
            return result;
        }

        private string GetCookieValue(string Name)
        {
            string value = "";
            if (HttpContext.Current.Request.Cookies[Name] != null)
                value = HttpContext.Current.Request.Cookies[Name].Value;
            return value;
        }

        private void SetCookie(string Name, string Value, DateTime ExpireDate, TimeSpan ExpireTime)
        {
            HttpCookie cookie = new HttpCookie(Name, Value);
            cookie.Expires = ExpireDate + ExpireTime;
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        private void SetCookie(string Name, string Value)
        {
            SetCookie(Name, Value, DateTime.Now, new TimeSpan(0,0,30,0));
        }

        private void SetCookie(string Name, int Value)
        {
            SetCookie(Name, Value.ToString());
        }


    }
}